package com.witsoft.device.config;

import com.witsoft.manager.MessageThreadHandler;
import com.witsoft.manager.QueueManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.util.concurrent.*;


@Slf4j
@Configuration
public class ThreadPoolConfig {

    //线程池维护线程的最小数量
    private final static int CORE_POOL_SIZE = 2;
    //线程池维护线程的最大数量
    private final static int MAX_POOL_SIZE = 10;
    //线程池维护线程所允许的空闲时间
    private final static int KEEP_ALIVE_TIME = 0;
    //线程池所使用的缓冲队列大小
    private final static int WORK_QUEUE_SIZE = 100;
    //队列最大长度
    private final static int QUEUE_CAPACITY_SIZE = 1000;

    @Resource
    private QueueManager queueManager;



    private final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            MessageThreadHandler event = (MessageThreadHandler) r;

            //消息加入到缓冲队列
            queueManager.offerMsg(event.getDeviceStatus());
            log.info("请求数过载，将过载的消息交给（调度线程池）逐一处理");
        }
    };


    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();

        threadPoolExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        threadPoolExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolExecutor.setQueueCapacity(WORK_QUEUE_SIZE);
        threadPoolExecutor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        threadPoolExecutor.setRejectedExecutionHandler(handler);

        return threadPoolExecutor;
    }



    @Bean(name="messageScheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService(){

        return Executors.newScheduledThreadPool(5);
    }
}
